<!--
  登录/注册模态框组件
  提供用户登录和注册功能，支持邮箱验证码注册
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="登录 / 注册"
    width="480px"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    @close="handleClose"
  >
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 登录标签页 -->
      <el-tab-pane label="登录" name="login">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="80px"
          @submit.prevent="handleLogin"
        >
          <el-form-item label="用户名/邮箱" prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名或邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="isLoading"
              @click="handleLogin"
              style="width: 100%"
            >
              {{ isLoading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
          <el-alert
            v-if="errorMessage"
            :title="errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </el-form>
      </el-tab-pane>

      <!-- 注册标签页 -->
      <el-tab-pane label="注册" name="register">
        <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="80px"
          @submit.prevent="handleRegister"
        >
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="请输入QQ邮箱"
              clearable
            />
          </el-form-item>
          <el-form-item label="验证码" prop="verify_code">
            <div style="display: flex; gap: 8px;">
              <el-input
                v-model="registerForm.verify_code"
                placeholder="请输入验证码"
                clearable
                style="flex: 1;"
              />
              <el-button
                :disabled="!canSendCode || countdown > 0"
                @click="handleSendCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="请输入密码（至少6位）"
              show-password
              clearable
            />
          </el-form-item>
          <el-form-item label="个人简介" prop="bio">
            <el-input
              v-model="registerForm.bio"
              type="textarea"
              :rows="3"
              placeholder="介绍一下自己...（可选）"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="isLoading"
              @click="handleRegister"
              style="width: 100%"
            >
              {{ isLoading ? '注册中...' : '注册' }}
            </el-button>
          </el-form-item>
          <el-alert
            v-if="errorMessage"
            :title="errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElDialog, ElTabs, ElTabPane, ElForm, ElFormItem, ElInput, ElButton, ElAlert } from 'element-plus'
import { useAuth } from '../composables/useAuth'
import { register } from '../api/client'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['update:visible', 'success'])

const authState = useAuth()
const activeTab = ref('login')
const loginFormRef = ref(null)
const registerFormRef = ref(null)

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
})

// 直接访问 state 属性，避免 computed ref 的类型问题
const isLoading = computed(() => authState.state.loading)
const errorMessage = computed(() => authState.state.error)

const loginForm = ref({
  username: '',
  password: '',
})

const registerForm = ref({
  email: '',
  password: '',
  verify_code: '',
  bio: '',
})

const countdown = ref(0)
const canSendCode = ref(true)

const loginRules = {
  username: [{ required: true, message: '请输入用户名或邮箱', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const registerRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  verify_code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' },
  ],
}

function handleClose() {
  dialogVisible.value = false
  // 重置表单和错误
  loginForm.value = { username: '', password: '' }
  registerForm.value = { email: '', password: '', verify_code: '', bio: '' }
  countdown.value = 0
  canSendCode.value = true
  authState.state.error = ''
  loginFormRef.value?.resetFields()
  registerFormRef.value?.resetFields()
}

function handleTabChange() {
  authState.state.error = ''
}

async function handleLogin() {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await authState.login(loginForm.value)
        emit('success')
        handleClose()
      } catch (error) {
        console.error('登录失败', error)
      }
    }
  })
}

async function handleSendCode() {
  if (!registerForm.value.email) {
    authState.state.error = '请先输入邮箱'
    return
  }

  // 验证邮箱格式
  const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailPattern.test(registerForm.value.email)) {
    authState.state.error = '邮箱格式不正确'
    return
  }

  try {
    canSendCode.value = false
    const { sendVerifyCode } = await import('../api/client')
    await sendVerifyCode({ email: registerForm.value.email })
    
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        canSendCode.value = true
      }
    }, 1000)
    
    authState.state.error = ''
  } catch (error) {
    console.error('发送验证码失败', error)
    authState.state.error = error?.message || '验证码发送失败，请稍后重试'
    canSendCode.value = true
  }
}

async function handleRegister() {
  if (!registerFormRef.value) return
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await register({
          email: registerForm.value.email,
          password: registerForm.value.password,
          verify_code: registerForm.value.verify_code,
          bio: registerForm.value.bio || undefined,
        })

        if (response?.token && response?.user) {
          // 注册成功后自动登录
          authState.state.user = response.user
          authState.state.token = response.token
          const { saveAuthSession } = await import('../api/client')
          saveAuthSession({
            token: response.token,
            user: response.user,
          })
          emit('success')
          handleClose()
        }
      } catch (error) {
        console.error('注册失败', error)
        authState.state.error = error?.message || '注册失败，请稍后再试'
      }
    }
  })
}

watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      activeTab.value = 'login'
      authState.state.error = ''
    }
  },
)
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px 24px;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-alert) {
  margin-top: 10px;
}
</style>


